package com.he.ymw.controller;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.he.ymw.pojo.SmsVo;
import com.he.ymw.pojo.User;
import com.he.ymw.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;
import java.util.Random;

/**
 * 处理用户的控制器
 */
@Controller
public class UserController {

    @Resource
    UserService userService;

    // 处理注册的方法
    @RequestMapping("/register")
    public String addUser(User user, @PathParam("smg")String smg,HttpSession session ,Model mv) {

        // 获取用户输入的手机号
        String mobile1 = (String) session.getAttribute("mobile");
        // 获取自动生成的验证码
        String captcha = (String) session.getAttribute("login" + mobile1);

        System.out.println("手机号:"+mobile1);
        System.out.println("自动生成的验证码:"+captcha);
        System.out.println("输入的验证码："+smg);
        System.out.println(user);

        // 如果输入的验证码和自动生成的验证码一致，则进入注册操作
        if (smg.equals(captcha)) {
            if (userService.addUser(user) > 0) {
                System.out.println("注册成功");
                // 将用户信息保存
                session.setAttribute("user",user);
                // 跳转到首页
                return "redirect:/index";
            } else {
                mv.addAttribute("smg","注册失败，请稍再在试");
                return "Regist";
            }
        } else {
            mv.addAttribute("smg","验证码输入错误");
            mv.addAttribute("user",user);
            return "Regist";
        }

    }

    /**
     * 跳转到登录界面
     */
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "Login";
    }

    /**
     * 跳转到注册界面
     */
    @RequestMapping("/toRegist")
    public String toRegist() {
        return "Regist";
    }

    /**
     * 判断用户名是否可用
     */
    @RequestMapping("/findUserName/{loginName}")
    @ResponseBody
    public boolean findUserName(@PathVariable String loginName) {
        // 查询用户名，如果用户名存在则返回true，否则返回false
        return null != userService.findUserName(loginName);
    }

    /**
     * 判断手机号是否可用
     */
    @RequestMapping("/findMobile/{mobile}")
    @ResponseBody
    public boolean findMobile(@PathVariable String mobile) {
        return null != userService.findMobile(mobile);
    }

    /**
     * 发送验证码
     */
    @RequestMapping("/sendCaptcha/{mobile}")
    @ResponseBody
    public boolean sendCaptcha(@PathVariable String mobile, HttpSession session) {
        try {
            DefaultProfile profile = DefaultProfile.getProfile("cn-qingdao", "LTAIDzry3H0QyTAK", "flz2LSsqSFLIO7WixnFLemVn5R1Enj");
            IAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.setSysMethod(MethodType.POST);
            request.setSysDomain("dysmsapi.aliyuncs.com");
            request.setSysVersion("2017-05-25");
            request.setSysAction("SendSms");
            request.putQueryParameter("PhoneNumbers", mobile);
            request.putQueryParameter("SignName", "1024平台");
            request.putQueryParameter("TemplateCode", "SMS_200710975");
            // 创建随机数
            Random random = new Random();
            // 定义captcha用来存放验证码
            StringBuilder captcha = new StringBuilder();
            // 循环四次，设置4位0-9的验证码
            for (int i = 0; i < 4; i++) {
                captcha.append(random.nextInt(10));
            }
            // 编写短信模板
            request.putQueryParameter("TemplateParam", "{\"code\":\"" + captcha + "\"}");
            CommonResponse response = client.getCommonResponse(request);
            String str = response.getData().toLowerCase();
            System.out.println(response.getData());
            SmsVo smsVo = new ObjectMapper().readValue(str, SmsVo.class);
//            if ("ok".equals(smsVo.getCode())) {
                // 保存验证码到  login+mobile ：key里
                session.setAttribute("login" + mobile, captcha.toString());
                // 设置验证码过期时间：5分钟
                session.setMaxInactiveInterval(60 * 5);
                // 保存手机号码
                session.setAttribute("mobile", mobile);
                System.out.println("验证码：" + captcha);
                System.out.println("手机号：" + mobile);
                // 发送成功返回true
                return true;
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 发送失败默认返回false
        return false;
    }

    /**
     * 通过账号密码登录的方法
     */
    @RequestMapping("/login")
    public String loginUsernamePassword(String loginName, String password, Model mv, HttpSession session ) {
        User user = userService.login(loginName, password);
        if (null == user) {
            // 将用户输入的数据还回去
            mv.addAttribute("msg","账号或密码输入错误请重新输入");
            mv.addAttribute("loginName",loginName);
            mv.addAttribute("password",password);
            return "Login";
        } else {
            session.setAttribute("user",user);
            return "redirect:/index";
        }
    }

    /**
     * 注销的方法
     */
    @RequestMapping("/logOut")
    public String logOut(HttpSession session) {
        session.removeAttribute("user");
        session.invalidate();
        return "redirect:index";
    }


}
